﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;

namespace Basmus.Values.Web
{
    public class RouteInfoService : IRouteInfoService
    {
        internal static readonly ConcurrentDictionary<Type, RouteAttribute[]> Cache =
            new ConcurrentDictionary<Type, RouteAttribute[]>();

        internal static IEnumerable<RouteAttribute> GetRouteAttributes(Type routeModelType)
        {
            return Cache.GetOrAdd(routeModelType, t =>
            {
                var attrs = t
                    .GetCustomAttributes(false)
                    .OfType<RouteAttribute>();
                return attrs.ToArray();
            });
        }

        public IRouteInfo GetRouteInfo(ModelContext modelContext)
        {
            var routeInfo = GetRouteAttributes(modelContext.TargetType)
                .Where(x => x.Key == modelContext.SchemeKey)
                .Select(x => new RouteInfo(x.Url, false))
                .FirstOrDefault();
            return routeInfo;

        }
    }
}